package com.aurora.app.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.aurora.app.entity.CategoryThing;
import com.aurora.app.entity.Help;
import com.aurora.app.entity.Location;
import com.aurora.app.entity.StoryTopic;
import com.aurora.app.entity.Thing;
import com.aurora.app.entity.ThingStory;
import com.aurora.app.entity.ThingStoryImage;
import com.aurora.app.entity.User;
import com.aurora.app.enums.HelpCategory;
import com.aurora.app.enums.PayCatatory;
import com.aurora.app.service.CategoryThingService;
import com.aurora.app.service.HelpService;
import com.aurora.app.service.LocationService;
import com.aurora.app.service.StoryTopicService;
import com.aurora.app.service.ThingService;
import com.aurora.app.service.ThingStoryImageService;
import com.aurora.app.service.ThingStoryService;
import com.aurora.app.util.StandardResponseBody;
import com.aurora.base.util.CreateResJosnUtil;

@Controller
@RequestMapping(value = "api/write")
public class WriteController {
	private final Logger LOG = LoggerFactory.getLogger(this.getClass());
	@Resource
	private CategoryThingService categoryThingService;
	@Resource
	private ThingService userThingService;
	@Resource
	private LocationService locationService;
	@Resource
	private HelpService helpService;
	@Resource
	private StoryTopicService storyTopicService;
	@Resource
	private ThingStoryImageService thingStoryImageService; 
	@Resource
	private ThingStoryService thingStoryService;
	/**
	 * 物品页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/thing")
	public ModelAndView thing(HttpServletRequest request,String thingId) {
		ModelAndView mv = new ModelAndView("write/writeThing");
		List<CategoryThing> listCategoryThing = this.categoryThingService.all();
		//List<Location> listLocation = this.locationService.all();
		mv.addObject("listCategoryThing", listCategoryThing);
		//mv.addObject("listLocation", listLocation);
		//if(StringUtils.isNotBlank(cs))
		return mv;
	}
	/**
	 * 物品页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/square")
	public ModelAndView square(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("write/writeSquare");
		List<StoryTopic> sList = this.storyTopicService.all();
		mv.addObject("sList", sList);
		return mv;
	}
	
	/**
	 * 物品页面
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/help")
	public ModelAndView help(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView("write/writeHelp");
		List<Location> listLocation = this.locationService.all();
		mv.addObject("listLocation", listLocation);
		return mv;
	}

	/**
	 * 确认物品发布
	 * 
	 * @param request
	 * @return
	 * @throws JSONException
	 */
	@ResponseBody
	@RequestMapping(value = "checkAndPublish", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String checkPublishThing(HttpServletRequest request, String categoryId, String images, String cost, String describle,
			String newDegree, String num, String originalCost, String outOfTime, String title, String phone,
			String location) {
		LOG.debug("start save thing");
		User user = (User) request.getSession().getAttribute("user");
		Thing thing;
		try {

			thing = this.userThingService.create2(categoryId,cost, describle, images, newDegree, num, originalCost, outOfTime,
					 title, phone, location, user);
			return CreateResJosnUtil.createSuccessJson(null, new JSONObject().put("id", thing.getId())).toString();
		} catch (Exception e) {
			return CreateResJosnUtil.createErrJson(e.getMessage()).toString();
		}

	}
	/**
	 * 确认帮帮任务发布
	 * @param request
	 * @param outOfTime
	 * @param money
	 * @param otherPay
	 * @param payCatatory
	 * @param title
	 * @param task
	 * @param helpCategory
	 * @param location
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "checkAndPublishHelp", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String checkPublishHelp(HttpServletRequest request,String outOfTime,Double money,String otherPay,int payCatatory,String title,String task,int helpCategory,String location) {
		LOG.debug("start save thing");
		User user = (User) request.getSession().getAttribute("user");
		Thing thing;
		try {
			Help help = new Help();
			//棒棒类型设置
			switch(helpCategory){
			case 0:
				help.setHelpCategory(HelpCategory.PackThing);
				break;
			case 1:
				help.setHelpCategory(HelpCategory.BugThing);
				break;
			case 2:
				help.setHelpCategory(HelpCategory.SendThing);
				break;
			}
			help.setLocation(this.locationService.get(location));
			//设置支付类型
			switch(payCatatory){
			case 0:
				help.setPayCatatory(PayCatatory.Money);
				help.setMoney(BigDecimal.valueOf(money));
				break;
			case 1:
				help.setPayCatatory(PayCatatory.Thing);
				help.setOtherPay(otherPay);
				break;
			}
			help.setTask(task);
			help.setTitle(title);
			help.setUser(user);
			this.helpService.save(help);
			return StandardResponseBody.Default(1, "", null);
		} catch (Exception e) {
			e.printStackTrace();
			return StandardResponseBody.Default(0,"棒棒任务新建失败",null);
		}
		
	}
	
	/**
	 * 确认广场文章发布
	 * @param request
	 * @param title
	 * @param topicId
	 * @param content
	 * @param serverIds
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/checkPublishSqure", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public String checkPublishSqure(HttpServletRequest request,String title,String topicId,String content,String serverIds){
		try{
			
			StoryTopic storyTopic = this.storyTopicService.get(topicId);
			if(storyTopic==null){
				return StandardResponseBody.Default(0,"找不到该话题",null);
			}
			ThingStory story = new ThingStory();
			User user  = (User)request.getSession().getAttribute("user");
			story.setUser(user);
			story.setStoryTopic(storyTopic);
			story.setContent(content);
			story.setTitle(title);
			
			
			this.thingStoryService.save(story);
			if(StringUtils.isNotBlank(serverIds)){
				String []serverId = serverIds.split(",");
				if(serverId.length!=0){
					for(String s :serverId){
						ThingStoryImage img = new ThingStoryImage();
						img.setPath(s);
						img.setThingStory(story);
						this.thingStoryImageService.save(img);
					}
				}
			}
			storyTopic.setStoryNum(storyTopic.getStoryNum()+1);
			this.storyTopicService.update(storyTopic);
			return StandardResponseBody.Default(1,"物语保存成功",null);
		}catch(Exception e){
			e.printStackTrace();
			return StandardResponseBody.Default(0,e.getMessage(),null);
		}
	}


	/**
	 * 确认发布 方法已废除
	 * 
	 * @param request
	 * @return
	 */
	public String check(HttpServletRequest request) {
		LOG.debug("start save thing");
		User user = (User) request.getSession().getAttribute("user");
		if (null == user) {
			LOG.debug("user not exist");
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("categoryId", request.getParameter("categoryId"));
		map.put("images", request.getParameter("images"));
		map.put("cost", request.getParameter("cost"));
		map.put("describle", request.getParameter("describle"));
		map.put("newDegree", request.getParameter("newDegree"));
		map.put("num", request.getParameter("num"));
		map.put("originalCost", request.getParameter("originalCost"));
		map.put("outOfTime", request.getParameter("outOfTime"));
		map.put("title", request.getParameter("title"));
		map.put("phone", request.getParameter("phone"));
		map.put("location", request.getParameter("location"));

		Thing thing;
		try {
			thing = this.userThingService.create(map, user);
			System.out.println(
					CreateResJosnUtil.createSuccessJson(null, new JSONObject().put("id", thing.getId())).toString());
			return CreateResJosnUtil.createSuccessJson(null, new JSONObject().put("id", thing.getId())).toString();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return CreateResJosnUtil.createErrJson(e.getMessage()).toString();
		}

	}
}
